const express = require("express");
const router = express.Router();
const passport = require("passport");
const Order = require("../../../models/Order");
const Shop = require("../../../models/Shop");
const auth = passport.authenticate("jwt", { session: false });
const errorHandler = require("../../../middlewares/errorHandler");

// 辅助函数：生成唯一订单号
function generateOrderNumber() {
  return "ORD-" + Date.now() + "-" + Math.floor(Math.random() * 10000);
}

// @route POST api/orders/add
router.post("/add", auth, async (req, res) => {
  try {
    const {
      items,
      shippingAddress,
      trackingNumber,
      estimatedDelivery,
      paidAmount,
    } = req.body;
    const user = req.user.id;
    const username = req.user.name;

    // 验证商品信息
    const validatedItems = [];
    for (const item of items) {
      const { productId, typeId, quantity } = item;

      const shop = await Shop.findOne({ "products._id": productId });
      if (!shop) {
        return res.status(404).json({ success: false, error: "未找到商品" });
      }

      const product = shop.products.id(productId);
      if (!product) {
        return res.status(404).json({ success: false, error: "未找到商品" });
      }

      const productType = product.types.id(typeId);
      if (!productType) {
        return res
          .status(404)
          .json({ success: false, error: "未找到商品类型" });
      }

      validatedItems.push({
        productId: product._id,
        typeId: productType._id,
        name: product.name,
        photo: productType.photo,
        type: productType.kind,
        price: productType.price,
        quantity,
      });
    }

    // 计算总金额
    const totalAmount = validatedItems
      .reduce(
        (total, item) => total + parseFloat(item.price) * item.quantity,
        0
      )
      .toFixed(2);

    // 确定订单状态
    const isPaid = parseFloat(paidAmount) > 0;
    let shippingStatus = "未付款";
    if (isPaid) {
      shippingStatus = trackingNumber ? "运输中" : "未发货";
    }

    // 创建新订单
    const newOrder = new Order({
      user,
      username,
      orderNumber: generateOrderNumber(),
      items: validatedItems,
      totalAmount,
      paidAmount,
      shippingAddress,
      trackingNumber,
      estimatedDelivery,
      isPaid,
      shippingStatus,
    });

    await newOrder.save();

    // 返回简化后的响应结构
    res.status(200).json({ success: true, data: { order: newOrder } });
  } catch (err) {
    errorHandler(res, err);
  }
});

// @route GET api/orders
router.get("/", auth, async (req, res) => {
  try {
    const orders = await Order.find({ user: req.user.id });
    if (!orders.length) {
      return res.status(404).json({ success: false, error: "没有订单" });
    }
    // 返回简化后的响应结构
    res
      .status(200)
      .json({ success: true, data: { orders, totalCount: orders.length } });
  } catch (err) {
    errorHandler(res, err);
  }
});

// @route PUT api/orders/update
router.put("/update", auth, async (req, res) => {
  try {
    const { orderId, updates } = req.body;
    const order = await Order.findOne({ user: req.user.id, _id: orderId });

    if (!order) {
      return res.status(404).json({ success: false, error: "未找到订单" });
    }

    let isStatusUpdated = false;

    if (updates.shippingStatus !== undefined) {
      order.shippingStatus = updates.shippingStatus;
      isStatusUpdated = true;
    }
    if (updates.isDelivered !== undefined) {
      order.isDelivered = updates.isDelivered;
      if (order.isPaid) {
        order.shippingStatus = "订单完成";
        isStatusUpdated = true;
      }
    }
    if (updates.isRefunded !== undefined) {
      order.isRefunded = updates.isRefunded;
      if (order.isPaid) {
        order.shippingStatus = "已取消";
        isStatusUpdated = true;
      }
    }
    if (updates.trackingNumber !== undefined) {
      order.trackingNumber = updates.trackingNumber;
      if (order.isPaid) {
        order.shippingStatus = "运输中";
        isStatusUpdated = true;
      }
    }
    if (updates.estimatedDelivery !== undefined) {
      order.estimatedDelivery = updates.estimatedDelivery;
    }
    if (updates.paidAmount !== undefined) {
      order.paidAmount = updates.paidAmount;
      order.isPaid = parseFloat(updates.paidAmount) > 0;
      if (order.isPaid && !isStatusUpdated) {
        order.shippingStatus = order.trackingNumber ? "运输中" : "未发货";
      } else if (!order.isPaid) {
        order.shippingStatus = "未付款";
      }
    }

    order.updatedAt = Date.now();
    await order.save();

    // 返回简化后的响应结构
    res.status(200).json({ success: true, data: { order } });
  } catch (err) {
    errorHandler(res, err);
  }
});

// @route DELETE api/orders/delete
router.delete("/delete", auth, async (req, res) => {
  try {
    const { orderId } = req.body;
    const order = await Order.findOneAndDelete({
      user: req.user.id,
      _id: orderId,
    });

    if (!order) {
      return res.status(404).json({ success: false, error: "未找到订单" });
    }

    // 返回简化后的响应结构
    res.status(200).json({ success: true, message: "订单删除成功" });
  } catch (err) {
    errorHandler(res, err);
  }
});

module.exports = router;
